package com.Cfeng.XiaohuanChat.controller;

import com.Cfeng.XiaohuanChat.domain.Resp;
import com.Cfeng.XiaohuanChat.entity.ChatUser;
import com.Cfeng.XiaohuanChat.entity.ChatUserRole;
import com.Cfeng.XiaohuanChat.repository.ChatUserRoleRepository;
import com.Cfeng.XiaohuanChat.service.ChatRoleService;
import com.Cfeng.XiaohuanChat.service.ChatUserService;
import com.Cfeng.XiaohuanChat.service.FileStoreService;
import com.mysql.cj.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/8/10
 * 处理当前登录用户
 */

@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/user")
public class ChatUserController {

    private final ChatUserService chatUserService;

    private final FileStoreService fileStoreService;

    private final ChatRoleService roleService;

    private final ChatUserRoleRepository roleRepository;

    /**
     * 根据name查询用户
     */
    @GetMapping("/query")
    public Resp<ChatUser> queryUser(String userName) {
        ChatUser chatUser = chatUserService.queryUser(userName);
        if(Objects.isNull(chatUser)) {
            return Resp.failed("用户名错误，没有该用户");
        }
        return Resp.ok(chatUser);
    }

    /**
     * 修改当前登录用户信息
     * save方法修改的字段的数据为
     */
    @PostMapping("/update")
    public Resp<ChatUser> updateUser(MultipartFile file, ChatUser chatUser) throws IllegalAccessException {
        //所以可以不用修改
        String chatUserUserPwd = chatUser.getUserPwd();
        chatUser.setUserPwd(BCrypt.hashpw(chatUserUserPwd,BCrypt.gensalt()));
        //文件上传到服务器
        String headerImgName =  fileStoreService.uploadFile(file);
        //文件上传后更新用户
        chatUser.setUserHeaderImg(headerImgName);
        log.info("更新用户信息，{}",chatUser);
        //持久化
        chatUserService.addOrUpdateUser(chatUser);
        return Resp.ok(chatUser);
    }

//    @GetMapping("/role")
//    public String changeRole(String userName) {
//        System.out.println(userName);
//        ChatUser chatUser = chatUserService.queryUser(userName);
//        //首先插入管理员角色
//        ChatUserRole userRole = roleRepository.findById(11).get();
//        //查看链表
//        System.out.println(userRole);
//        chatUser.getRoles().add(userRole);
////        chatUser.setRoles(Arrays.asList(userRole));
//        ChatUserRole role = new ChatUserRole();
//        role.setRoleName("user");
//        roleRepository.save(role);  修改中间表都需要其他的save语句带动
//        return "修改成功";
//    }

    @GetMapping(value = "/downloadHeadImg",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<Resource> downloadHeadImg(@RequestParam("userName") String userName) throws FileNotFoundException {
        //查询用户获得头像名称，再下载
        ChatUser chatUser = chatUserService.queryUser(userName);
        String imgName = chatUser.getUserHeaderImg();
        if(StringUtils.isNullOrEmpty(imgName)) {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
        Resource resource = fileStoreService.loadFile(imgName);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=" + URLEncoder.encode(imgName, StandardCharsets.UTF_8));
        return ResponseEntity.ok().headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @GetMapping("/delete")
    public Resp<String> removeUser(String userName) {
        chatUserService.removeUser(chatUserService.queryUser(userName));
        return Resp.ok(userName + "删除成功");
    }
}
